package com.richapp.launcher.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import com.jack.netty.log.LoggerManager;
import com.richapp.launcher.busevent.EventServiceDestroy;
import com.richapp.launcher.gpio.GPIOServer;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.service.RemoteService;
import com.richapp.launcher.ui.activities.RestartTip;
import com.richapp.launcher.ui.activities.StartActivity;
import com.richapp.launcher.utils.Tools;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

/**
 * Created by jack on 15/12/25.
 */
public class NetWorkChangeReceiver extends BroadcastReceiver {
    Context context1;
    boolean wifiFlag = false;
    boolean lanFlag = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo lanNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        context1=context;



        if(wifiNetInfo != null){
            if(wifiNetInfo.isConnected()){
                wifiFlag = true;
                Intent intent1= new Intent(context,StartActivity.class);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent1);
                String distributor=Tools.getDistributorSerial();
                Toast.makeText(context,"WIFI已连接"+distributor,Toast.LENGTH_SHORT).show();

            }
        }

        if(lanNetInfo != null){
            if(lanNetInfo.isConnected()){
                lanFlag = true;
                lanNetInfo.getState();

                Intent intent1= new Intent(context,StartActivity.class);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent1);
                String distributor=Tools.getDistributorSerial();
                Toast.makeText(context,"有线网络已连接"+distributor,Toast.LENGTH_SHORT).show();


            }else {
                List<String> ips = Tools.getAllIps(0);
                String ip0 = "";

                if(ips.size() > 0){
                    ip0 = ips.get(0);
                }

                if ("".equals(ip0)) {
                    Log.v("NetWorkChangeReceiver", "检测到网络异常");
                    Intent intent1 = new Intent(context, RestartTip.class);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent1);
                    if (!wifiFlag || !lanFlag) { //判断网络是否可用 如不可用进入方法
                        delayed();
                    }else {
                        return;

                    }
                }

            }
        }

        if(wifiFlag || lanFlag){
            GPIOServer.getInstance().openWifiLight();
            GPIOServer.getInstance().openLanLight();
        }

        if(!wifiFlag && !lanFlag){
            GPIOServer.getInstance().closeWifiLight();
            GPIOServer.getInstance().closeLanLight();
        }

        /*if(mobNetInfo != null){
            if(mobNetInfo.isConnected()){

            }else{

            }
        }*/
    }

    /**
     * 延迟器
     */
    public void  delayed(){
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                List<String> Lip = Tools.getAllIps(0);
                String ip1 = "";
                if(Lip.size() > 0){
                    ip1 = Lip.get(0);
                }
                if ("".equals(ip1)){
                    if(!wifiFlag || !lanFlag){
                        Tools.restartSystem(context1);
                    }else {
                        return;
                    }
                }

            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000*60);//60秒后执行TimeTask的run方法


    }


    //监听网络改变的时候做远程服务器的服务销毁或启动动作
    public void  delayedStopRemoteClient(){
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                if (!Tools.ping()){
                    if(Tools.isServiceRun(context1, RemoteService.class.getName())){
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                RemoteClient.getInstance().stop();
                                LoggerManager.getInstance().getiLogger().info(getClass(), "外网服务器连接服务销毁!");
                                EventBus.getDefault().post(new EventServiceDestroy(RemoteService.class));
                            }
                        }).start();

                    }
                }else {
                    if(!Tools.isServiceRun(context1, RemoteService.class.getName())){
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                RemoteClient.getInstance().start();
                                //保持服务
                                LoggerManager.getInstance().getiLogger().info(getClass(),"外网服务器连接服务启动!");
                            }
                        }).start();

                    }
                }


            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000*30);//60秒后执行TimeTask的run方法


    }

}
